package it.hive.controller.task;

import it.hive.model.common.ApplicationProperties;
import it.hive.model.common.constants.M2O_Default;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javafx.concurrent.Task;

public class CheckInternetConnection extends Task<Boolean> {

	public CheckInternetConnection() {
		new Thread(this).start();
	}

	@Override
	protected Boolean call() throws Exception {
		InputStream stream = null;
		updateProgress(-1, 100);

		Thread t = animazioneTesto(getMessage(), "Connessione in corso . . . . . .");
		if (ApplicationProperties.proxyIP.get() != null && ApplicationProperties.proxyPort.get() != null) {
			System.setProperty("http.proxyHost", ApplicationProperties.proxyIP.get());
			System.setProperty("http.proxyPort", ApplicationProperties.proxyPort.get());
		}

		try {
			t.join();
			HttpURLConnection urlCon = (HttpURLConnection) new URL(M2O_Default.M2O_RELOADED_URL).openConnection();
			urlCon.setConnectTimeout(4 * 1000);
			urlCon.setRequestMethod("GET");
			urlCon.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
			urlCon.connect();
			boolean internetConnection = (stream = urlCon.getInputStream()) != null && stream.read() != -1;

			updateProgress(100, 100);
			ApplicationProperties.internetConnection.set(internetConnection);
			if (internetConnection) {
				animazioneTesto(getMessage(), "Connessione effettuata!                    ").join();
				animazioneTesto(getMessage(), "M2O Reloaded - Download & Play").join();
			} else {
				animazioneTesto(getMessage(), "Impossibile contattare il server! Assicurati di essere connesso ad internet.").join();
			}
			return internetConnection;
		} catch (IOException e) {
			// updateMessage("Impossibile contattare il server! proxy?");
			ApplicationProperties.internetConnection.set(false);
			animazioneTesto(getMessage(), "Impossibile contattare il server! Assicurati di essere connesso ad internet.").join();
			return false;
		} finally {
			if (stream != null) {
				stream.close();
			}
			updateProgress(100, 100);
		}
	}

	private Thread animazioneTesto(final String oldString, final String newText) {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = oldString.length(); i != 0; i--) {
					updateMessage(oldString.substring(0, i));
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						System.out.println(e.getMessage());
					}
				}
				for (int i = 0; i <= newText.length(); i++) {
					updateMessage(newText.substring(0, i));
					try {
						Thread.sleep(20);
					} catch (InterruptedException e) {
					}
				}
			}
		});
		t.start();
		return t;
	}
}
